Referencing HTML elements inside Shadow DOM - HTMHell
Referencing HTML elements inside Shadow DOM - HTMHell
mehm8128がHTMHell Advent Calendar 2025に寄稿した記事
Web Componentsの課題として<label for="checkbox"> が Shadow DOM内の <input> と関連付けできない問題がある
解決策
単一要素参照のためのshadowRootReferenceTargetを導入
code:html
<div>
<label for="checkbox">I agree with the terms and conditions</label>
<fancy-checkbox id="checkbox">
<template shadowrootmode="open" shadowRootReferenceTarget="inner-checkbox">
<input type="checkbox" id="inner-checkbox" />
</template>
</fancy-checkbox>
</div>
code:html
<div>
<input type="text" aria-labelledby="label" />
<fancy-label id="label">
<template shadowrootmode="open" shadowRootReferenceTarget="inner-label">
<label id="inner-label">Type your name.</label>
</template>
</fancy-label>
</div>
Google Chrome Canaryで試せる
複数要素参照のためのshadowRootReferenceTargetMap属性を導入
複数の参照(例: aria-controls, aria-activedescendant)をShadow DOM内の要素にマッピング可能になる
code:html
<input
role="combobox"
type="text"
aria-controls="animals"
aria-activedescendant="animals"
/>
<animals-listbox id="animals">
<template
shadowrootmode="open"
shadowRootReferenceTargetMap="aria-controls: listbox,
aria-activedescendant: opt1"
<div role="listbox" id="listbox">
<div role="option" id="opt1">Otter</div>
<div role="option" id="opt2">Opossum</div>
<div role="option" id="opt3">Ocelot</div>
</div>
</template>
</animals-listbox>